// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import { postAnswer } from "@/services//answer";

interface AnswerItem {
  componentId: string;
  value: string | string[]; // 根据表单数据，可能是单个值或数组
}

interface AnswerInfo {
  questionId: string;
  answerList: AnswerItem[];
}
function genAnswerInfo(reqBody: Record<string, string[]>): AnswerInfo {
  const answerList: AnswerItem[] = [];
  Object.keys(reqBody).forEach((key) => {
    if (key === "questionId") return;
    answerList.push({
      componentId: key,
      value: reqBody[key],
    });
  });
  return {
    questionId: reqBody.questionId[0],
    answerList,
  };
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== "POST") {
    return res.status(405).json({ code: 405, message: "Method not allowed" });
  }
  try {
    const answerInfo = genAnswerInfo(req.body);
    const result = await postAnswer(answerInfo);
    if (result.code === 200) {
      res.redirect("/success");
    } else {
      res.redirect("/fail");
    }
  } catch (err) {
    console.log(err);
    res.redirect("/fail");
  }
}
